/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.box.jsch

import com.jcraft.jsch.ChannelExec
import com.jcraft.jsch.Session
import javax.inject.Inject
import org.apache.commons.io.IOUtils
import org.slf4j.LoggerFactory
import cool.taomu.box.inter.IDataSource

class Ssh implements AutoCloseable {
	val static LOG = LoggerFactory.getLogger(Ssh);
	ChannelExec exec = null;
	IDataSource ds;
	Session session;

	@Inject
	new(IDataSource ds) {
		LOG.info("创建SSH Channel");
		this.ds = ds;
	}

	def exec(String cmd, String charset) {
		this.session = ds.resource;
		var channel = session.openChannel("exec");
		this.exec = channel as ChannelExec;
		exec.command = cmd;
		exec.connect;
		var input = exec.inputStream;
		return IOUtils.toString(input, charset);
	}

	override close() throws Exception {
		if (exec !== null) {
			LOG.info("关闭SSH Channel");
			this.exec.disconnect
			this.session.disconnect
		}
	}
}
